<template>
  <div
    class="file-scan"
    v-loading="loading"
    element-loading-text="扫描中..."
    :element-loading-spinner="svg"
    element-loading-svg-view-box="-10, -10, 50, 50"
    element-loading-background="rgba(122, 122, 122, 0.8)"
  >
    <splitpanes :dbl-click-splitter="false" class="default-theme">
      <pane :size="70">
        <el-card>
          <div class="left-top">
            <div class="left">
              <div class="icons-item">
                <el-tooltip class="box-item" effect="dark" content="删除当前页" placement="top-start">
                  <i class="iconfont icon-shanchuyemian" @click="delSinglePage"></i>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="删除全部" placement="top-start">
                  <i class="iconfont icon-piliangshanchu" @click="delAllPage"></i>
                </el-tooltip>
                <el-tooltip v-if="scanFrom != 'FullText'" class="box-item" effect="dark" content="文件" placement="top-start">
                  <i class="iconfont icon-wenjianshu" @click="nodeDrawer = true"></i>
                </el-tooltip>
              </div>
              <div class="current-page">{{ currentPageIndex }} / {{ imagesUrls?.length ?? 0 }}</div>
            </div>
            <div class="right">
              <div class="scale">
                <el-tooltip class="box-item" effect="dark" content="缩小" placement="top-start">
                  <el-icon @click="scaleHandle(-1)"><Minus /></el-icon>
                </el-tooltip>
                <div class="count">{{ curScaleValue }}%</div>
                <el-tooltip class="box-item" effect="dark" content="放大" placement="top-start">
                  <el-icon @click="scaleHandle(1)"><Plus /></el-icon>
                </el-tooltip>
              </div>
              <div class="right-icons">
                <el-tooltip class="box-item" effect="dark" content="开始裁剪" placement="top-start">
                  <i class="iconfont icon-shubiaoyidong-anse" @click="start"></i>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="裁剪" placement="top-start">
                  <i class="iconfont icon-caijian" @click="trimClick"></i>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="向左旋转" placement="top-start">
                  <i class="iconfont icon-zuoshunshizhenxuanzhuan" @click="rotateHandle('left')"></i>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="向右旋转" placement="top-start">
                  <i class="iconfont icon-youshunshizhenxuanzhuan" @click="rotateHandle('right')"></i>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="重置" placement="top-start">
                  <i class="iconfont icon-yuanxunhuan" @click="reset"></i>
                </el-tooltip>
              </div>
            </div>
          </div>
          <div class="left-content">
            <div class="small-previw" ref="smallPreviw">
              <div
                class="preview-item"
                v-for="(url, index) in imagesUrls"
                :key="index"
                :style="{ borderColor: curImgIndex === index ? 'rgb(0 150 136)' : '#cccccc' }"
                @click="imgClickHandle(url, index)"
              >
                <img :src="url" />
                <div class="order">{{ index + 1 }}</div>
              </div>
            </div>
            <div class="big-preview">
              <CustomCropper ref="cropperRef" :showToolBar="false" :curNodeImgUrl="curNodeImgUrl" @imgCroped="imgCropedHandle" />
            </div>
          </div>
        </el-card>
      </pane>
      <pane :size="30">
        <el-card>
          <div class="top-wrap">
            <div class="right-title">文件配置</div>
            <div class="top-config">
              <div v-if="scanFrom != 'FullText'" class="config-item">
                <div class="label">文件目录：</div>
                <div class="content">
                  <el-input v-model="fileDirectory" placeholder="请输入" />
                  <el-tooltip class="box-item" effect="dark" content="更新目录名称" placement="top-start">
                    <el-icon @click="handleChangeDic"><Refresh /></el-icon>
                  </el-tooltip>
                </div>
              </div>
              <div class="config-item">
                <div class="label">文件名称:</div>
                <div class="content">
                  <el-input v-model="fileName" placeholder="请输入" />
                  <div class="pointer">.</div>
                  <!-- <el-select v-model="fileSuffix" placeholder="Select" style="width: 130px">
                  <el-option v-for="item in fileSuffixOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
                  <el-select v-model="saveType" placeholder="Select" style="width: 140px" @change="toggleFormatOptions">
                    <el-option v-for="item in saveFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                  <el-tooltip class="box-item" effect="dark" content="更新文件名称" placement="top-start">
                    <el-icon @click="handleChangeFile"><Refresh /></el-icon>
                  </el-tooltip>
                </div>
              </div>
              <div class="config-item">
                <div class="label">扫描设备：</div>
                <el-select v-model="scanDevice" placeholder="请选择扫描设备">
                  <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <!-- <div class="config-item">
              <div class="label">保存格式：</div>
              <el-select v-model="saveType" placeholder="Select" @change="toggleFormatOptions">
                <el-option v-for="item in saveFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div> -->
              <div class="config-item" v-if="saveType == 'jpg'">
                <div class="label">JPEG 质量：</div>
                <el-input v-model="imageQuality" placeholder="（0-100）" />
              </div>
              <div class="config-item" v-if="saveType == 'tiff'">
                <div class="label">TIFF 压缩：</div>
                <el-select v-model="tifZipStyle" placeholder="Select" @change="toggleFormatOptions">
                  <el-option v-for="item in tifZipOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="config-item splitCount" v-if="saveType == 'pdf'">
                每
                <el-input v-model="splitCount" style="width: 100px; margin: 0 4px" placeholder="页数" />保存为一个文件
              </div>

              <div class="config-item high-config">
                <div class="check-group">
                  <el-checkbox v-model="useOriginalUi" label="扫描仪原生界面" @change="toggleScanOptions" />
                  <el-checkbox v-model="delEmptyPage" label="排除多余空白页" @change="toggleBlankPageOptions" />
                  <el-checkbox v-model="expendPageSize" label="扩展至纸张大小" />
                  <el-checkbox v-model="cropPageSize" label="裁剪至页面大小" />
                </div>
                <div class="empty-page">
                  <div class="config-value">
                    <span>白色阈值：</span>
                    <el-input v-model="whiteValue" :disabled="delEmptyPage" placeholder="Please input" />
                  </div>
                  <div class="config-value">
                    <span>空白覆盖率阈值：</span>
                    <el-input v-model="whiteRateValue" :disabled="delEmptyPage" placeholder="Please input" />
                  </div>
                </div>
              </div>
              <div class="verticle-item">
                <div class="label">DPI分辨率：</div>
                <el-select v-model="dpi" placeholder="Select">
                  <el-option v-for="item in dpiOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="verticle-item">
                <div class="label">像素类型：</div>
                <el-select v-model="bitdepth" placeholder="Select">
                  <el-option v-for="item in bitdepthOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </div>
          </div>

          <!-- 按钮组 -->
          <div class="btn-wrap">
            <div class="right-title">操作</div>
            <div class="btn-group">
              <el-button class="save-config" type="primary" plain @click="configDrawer = true">
                <i class="iconfont icon-typewriter"></i>
                配置
              </el-button>
              <el-button class="save-config" type="primary" plain @click="scan">
                <i class="iconfont icon-duomeiti-1"></i>
                扫描
              </el-button>
              <el-button
                v-if="props.scanFrom != 'FullText'"
                class="save-config"
                type="primary"
                plain
                @click="downloadScanned('download')"
              >
                <i class="iconfont icon-download-2"></i>
                下载
              </el-button>
              <el-button v-else class="save-config upload-btn" type="primary" plain @click="downloadScanned('upload')">
                <el-icon><Upload /></el-icon>
                上传
              </el-button>
              <input
                type="file"
                ref="fileInput"
                accept=".jpg,.jpeg,.png,.pdf"
                multiple
                style="display: none"
                @change="handleFileChange"
              />
              <el-button class="save-config" type="primary" plain @click="uploadFile">
                <i class="iconfont icon-w_daorudao-"></i>
                导入
              </el-button>
              <el-button class="save-config" type="primary" plain @click="clearImages">
                <i class="iconfont icon-qingkong"></i>
                清空
              </el-button>
            </div>
          </div>
        </el-card>
      </pane>
    </splitpanes>
    <el-drawer v-model="configDrawer" :with-header="false" size="40%">
      <el-card>
        <div class="right-title">基础配置</div>
        <div class="basic-config">
          <div class="basic-item">
            <div class="label">当前配置：</div>
            <el-select v-model="currentConfig" placeholder="请选择配置" @change="loadProfileSettings">
              <el-option v-for="item in configOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="basic-item">
            <div class="label">配置名称：</div>
            <el-input v-model="configName" placeholder="请输入新配置名称" />
          </div>
          <!-- 保存配置按钮 -->
          <el-button class="save-config" type="primary" plain @click="saveProfile(true)">
            <i class="iconfont icon-baocun"></i>
            保存配置
          </el-button>
        </div>
      </el-card>
      <!-- <el-card>
        <div class="right-title">高级配置</div>
        <div class="high-config">
          <el-checkbox v-model="useOriginalUi" label="使用扫描仪原生界面" @change="toggleScanOptions" />
          <div class="empty-page">
            <el-checkbox v-model="delEmptyPage" label="排除空白页" @change="toggleBlankPageOptions" />
            <div class="config-value">
              <span>白色阈值：</span>
              <el-input v-model="whiteValue" :disabled="delEmptyPage" style="width: 281px" placeholder="Please input" />
            </div>
            <div class="config-value">
              <span>空白覆盖率阈值：</span>
              <el-input v-model="whiteRateValue" :disabled="delEmptyPage" style="width: 240px" placeholder="Please input" />
            </div>
          </div>
          <el-checkbox v-model="expendPageSize" label="扩展至纸张大小" />
          <el-checkbox v-model="cropPageSize" label="裁剪至页面大小" />
        </div>
      </el-card> -->
      <el-card>
        <div class="right-title">扫描配置</div>
        <div class="scan-config">
          <div class="scan-item">
            <div class="label">驱动类型：</div>
            <el-select v-model="driverType" placeholder="Select" @change="driverTypeChoose">
              <el-option v-for="item in driverOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="scan-item">
            <div class="label">扫描来源：</div>
            <el-select v-model="sourceValue" placeholder="Select">
              <el-option v-for="item in scanSourceOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="scan-item">
            <div class="label">纸张大小：</div>
            <el-input v-model="pagesize" placeholder="如 A4, Letter 可输入长宽尺寸,形如：210x275mm" />
          </div>
          <!-- <div class="scan-item">
            <div class="label">DPI：</div>
            <el-select v-model="dpi" placeholder="Select">
              <el-option v-for="item in dpiOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="scan-item">
            <div class="label">像素类型：</div>
            <el-select v-model="bitdepth" placeholder="Select">
              <el-option v-for="item in bitdepthOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div> -->
          <!-- <div class="checkgroup">
            <el-checkbox v-model="check" label="显示扫描仪UI" />
            <el-checkbox v-model="check" label="自动删除空白页" />
            <el-checkbox v-model="check" label="双面扫描" />
          </div> -->
          <!-- <el-button class="save-config" type="primary" plain>
            <i class="iconfont icon-duomeiti-1"></i>
            扫描
          </el-button> -->
        </div>
      </el-card>
    </el-drawer>
    <el-drawer v-model="nodeDrawer" title="文件扫描节点" direction="rtl" :size="260">
      <el-tree
        v-if="nodeDrawer"
        ref="treeRef"
        :data="filenodes"
        :props="{
          children: 'children',
          label: 'name'
        }"
        node-key="name"
        highlight-current
        @node-click="selectNode"
      >
        <template #default="{ data, node }">
          <div class="parent-node" :title="data.name">
            <img
              v-if="data.isDirectory"
              :src="node.expanded ? openedFolder : closedFolder"
              style="width: 16px; margin-right: 5px"
            />
            <img v-else src="@/assets/imgs/file.png" style="width: 16px; margin-right: 5px" />
            <span>{{ data.name }}</span>
          </div>
        </template>
      </el-tree>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import axios from "axios";
import { reactive, ref, onMounted, nextTick } from "vue";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import useCurrentInstance from "@/utils/useCurrentInstance";
import CustomCropper from "../cropperBoard/CustomCropper.vue";
import mittBus from "@/utils/mittBus";
import openedFolder from "@/assets/imgs/opened_folder.png";
import closedFolder from "@/assets/imgs/folder.png";
import { getSysConfig, base64ToFile } from "@/utils/util";
const check = ref(false);
const { proxy } = useCurrentInstance();
const curScaleValue = ref(0); // 放大倍数
const fileDirectory = ref("FN-2025-Y-0001"); // 文件夹名称
const fileName = ref("FN-2025-Y-0001_0001"); // 文件名称
const nodeDrawer = ref(false); // 节点抽屉
const filenodes = ref(); // 节点数据
const initCount = ref(1); // 文件名数字初始化
const firstCount = ref(true); // 是否是第一次计数

const props = defineProps({
  scanFrom: {
    type: String,
    default: "page"
  },
  fatherObj: {
    type: Object,
    default: () => ({})
  }
});

// 当前配置
const configOptions = reactive([
  {
    label: "测试---占位",
    value: "0"
  },
  {
    label: "-- 新配置 --",
    value: ""
  }
]); // 当前配置信息

// 扫描来源
const scanSourceOptions = [
  {
    label: "Glass",
    value: "Glass"
  },
  {
    label: "Feeder",
    value: "Feeder"
  },
  {
    label: "Duplex",
    value: "Duplex"
  }
];

// dpi分辨率
const dpiOptions = [
  {
    label: "100",
    value: "100"
  },
  {
    label: "150",
    value: "150"
  },
  {
    label: "200",
    value: "200"
  },
  {
    label: "300",
    value: "300"
  }
];

// 位深
const bitdepthOptions = [
  {
    label: "Color",
    value: "color"
  },
  {
    label: "Gray",
    value: "gray"
  },
  {
    label: "Black & White",
    value: "bw"
  }
];

// 驱动类型
const driverOptions = [
  {
    label: "TWAIN",
    value: "twain"
  },
  {
    label: "WIA",
    value: "wia"
  }
];

// 保存格式
const saveFormatOptions = reactive<any>([
  {
    label: "JPG",
    value: "jpg"
  },
  {
    label: "PDF",
    value: "pdf"
  },
  {
    label: "TIFF",
    value: "tiff"
  }
]);

// tif压缩方式
const tifZipOptions = reactive<any>([
  {
    label: "AUTO",
    value: "auto"
  },
  {
    label: "LZW",
    value: "lzw"
  },
  {
    label: "CCITT4",
    value: "ccitt4"
  },
  {
    label: "None",
    value: "none"
  }
]);

// 扫描设备
const deviceOptions = reactive<any>([]);

const configDrawer = ref(false);

// 基础配置
const currentConfig = ref(""); // 当前配置
const configName = ref(""); // 配置名称

// 高级配置
const useOriginalUi = ref(false); // 使用扫描仪原生界面
const delEmptyPage = ref(false); // 排除空白页
const whiteValue = ref(70); // 白色阈值
const whiteRateValue = ref(25); // 空白覆盖率阈值
const expendPageSize = ref(false); // 扩展至纸张大小
const cropPageSize = ref(false); // 裁剪至页面大小

// 扫描配置
const driverType = ref("twain"); // 驱动类型
const scanDevice = ref(""); // 扫描设备
const sourceValue = ref("Glass"); // 扫描来源
const pagesize = ref(""); // 纸张大小
const dpi = ref("100"); // dpi大小
const bitdepth = ref("Color"); // 位深
const saveType = ref("jpg"); // 保存格式
const imageQuality = ref(75); // 图片质量
const tifZipStyle = ref("auto"); // tif压缩方式
const splitCount = ref(null); // 每多少页为一个文件

// 扫描得到的图片
const images = ref<any>([]);
// 小型缩略图
const smallPreviw = ref<any>(null);

// 扫描图片得到的图片路径
const imagesUrls = ref<any>([]);

// 当前扫描的图片
const curNodeImgUrl = ref<string>("");

// 当前选中缩略图下标
const curImgIndex = ref<any>(null);

// 上传图片节点
const fileInput = ref();

// 当前页面索引
const currentPageIndex = ref(0);

const cropperRef = ref(); // 裁剪组件

const loading = ref(false); // 扫描加载
const svg = `
    <path class="path" d="
      M 30 15
      L 28 17
      M 25.61 25.61
      A 15 15, 0, 0, 1, 15 30
      A 15 15, 0, 1, 1, 27.99 7.5
      L 15 15
    " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
  `;

// 左侧滚动到底部
const scrollToBottom = () => {
  if (smallPreviw.value) {
    smallPreviw.value.scrollTo({
      top: smallPreviw.value.scrollHeight,
      behavior: "smooth" // 可选，平滑滚动
    });
    // 或者简写为：
    // scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
  }
};

// 裁剪处理
const imgCropedHandle = (croppedImgUrl: string) => {
  curNodeImgUrl.value = croppedImgUrl;
  imagesUrls.value[curImgIndex.value] = croppedImgUrl;
  if (props.scanFrom != "FullText") {
    const file = base64ToFile(croppedImgUrl, `${fileName.value}.${saveType.value}`, "image/jpg");
    const formData = new FormData();
    formData.append("file", file);

    axios({
      url: `api/api/MasterFile/files?path=${fileDirectory.value}`,
      method: "post",
      data: formData
    }).then(res => {
      console.log("文件上传成功!!!", res);
      getTreeNodeData();
    });
  }
};

// 缩略图预览区
const imgClickHandle = (url: string, i: number) => {
  curNodeImgUrl.value = url;
  curImgIndex.value = i;
  currentPageIndex.value = imagesUrls.value?.findIndex((item: string) => item == curNodeImgUrl.value) + 1;
};

// 点击抽屉中的树节点
const selectNode = (node: any) => {
  if (!node?.children || !node?.children.length) return;
  fileDirectory.value = node?.path;
  curNodeImgUrl.value = "";
  getFilesDataList(node);
};

// 获取指定的文件夹数据
const getFilesDataList = (node: any) => {
  imagesUrls.value = [];
  axios({
    url: `api/api/MasterFile/files?path=${node.path}`,
    method: "get"
  }).then(res => {
    console.log("获取指定文件夹文件数据", res);
    if (res?.data?.Children.length) {
      res?.data?.Children.forEach(async (item: any) => {
        const result = await axios.get("api/api/MasterFile/file-stream", {
          responseType: "arraybuffer",
          params: {
            path: item.Path
          }
        });
        const contentType = result.headers["content-type"] || "image/jpeg";
        const blob = new Blob([result.data], { type: contentType });
        const reader = new FileReader();
        reader.onloadend = () => {
          imagesUrls.value.push(reader.result as string);
          if (res?.data?.Children.length == imagesUrls.value.length) {
            initCount.value = imagesUrls.value.length;
            fileName.value = `${node?.path}_${initCount.value.toString().padStart(4, "0")}`;
          }
        };
        reader.readAsDataURL(blob);
      });
    }
  });
};

// 保存基础配置
const saveProfile = (flag: boolean) => {
  // 暂时注释
  if (!configName.value?.trim()) {
    proxy.$message.warning("请填写配置名称！");
    return;
  }
  const clamp = (v: any, min: any, max: any) => Math.max(min, Math.min(max, v));
  const data = {
    origin_name: currentConfig.value, // 当前配置
    name: configName.value, // 配置名称
    driver: driverType.value, // 驱动类型
    source: sourceValue.value, // 扫描来源
    pagesize: pagesize.value, // 纸张大小
    dpi: dpi.value, // dpi像素
    bitdepth: bitdepth.value, // 像素类型
    use_native_ui: useOriginalUi.value, // 使用扫描仪原生界面
    force_pagesize: expendPageSize.value, // 扩展至纸张大小
    force_pagesize_crop: cropPageSize.value, // 裁剪至页面大小
    exclude_blank_pages: delEmptyPage.value, // 排除空白页
    white_threshold: clamp(whiteValue.value || 70, 0, 100),
    coverage_threshold: clamp(whiteRateValue.value || 25, 0, 100)
  };

  fetch(getSysConfig("fileScanGetprofiles"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  })
    .then(res => res.json())
    .then(result => {
      if (result.error) {
        alert("配置保存失败：" + result.error);
      } else {
        if (flag) {
          alert("配置已保存：" + result.name);
          loadProfileList();
        }
      }
    });
};

function loadProfileList() {
  fetch(getSysConfig("fileScanGetprofiles"))
    .then(res => res.json())
    .then(names => {
      names.forEach((name: any) => {
        const opt = document.createElement("option");
        configOptions.push({
          label: name,
          value: name
        });
      });
    });
}

function loadDevices() {
  fetch(`${getSysConfig("fileScanGetDevices")}?driver=${driverType.value}`)
    .then(res => res.json())
    .then(data => {
      data.devices.forEach((dev: any) => {
        deviceOptions.push({
          label: dev,
          value: dev
        });
      });
      scanDevice.value = deviceOptions[0]?.value;
    });
}

// 驱动类型选择
const driverTypeChoose = (val: string) => {
  driverType.value = val;
  loadDevices();
  loadProfileList();
};

const loadProfileSettings = (val: string) => {
  if (!val) return;
  currentConfig.value = val;
  fetch(`/profiles/${val}`)
    .then(res => res.json())
    .then(profile => {
      configName.value = val;
      if (profile.DriverName) loadDriverLight(profile.DriverName);
      if (profile.Device?.Name) scanDevice.value = profile.Device.Name;
      if (profile.PaperSource) sourceValue.value = profile.PaperSource;
      if (profile.PageSize) pagesize.value = profile.PageSize;
      if (profile.Resolution) {
        const dpi = profile.Resolution.replace("Dpi", "");
        dpi.value = dpi;
      }
      if (profile.BitDepth) {
        const map: any = { C24Bit: "color", Grayscale: "gray", BlackAndWhite: "bw" };
        bitdepth.value = map[profile.BitDepth] || "color";
      }
      if (profile.UseNativeUI) {
        useOriginalUi.value = profile.UseNativeUI === "true";
      }
      if (profile.ForcePageSize) {
        expendPageSize.value = profile.ForcePageSize === "true";
      }
      if (profile.ForcePageSizeCrop) {
        cropPageSize.value = profile.ForcePageSizeCrop === "true";
      }

      if (profile.ExcludeBlankPages) delEmptyPage.value = profile.ExcludeBlankPages === "true";
      if (profile.BlankPageWhiteThreshold) whiteValue.value = profile.BlankPageWhiteThreshold;
      if (profile.BlankPageCoverageThreshold) whiteRateValue.value = profile.BlankPageCoverageThreshold;

      toggleBlankPageOptions();
      toggleScanOptions();
    });
};

function loadDriverLight(driver: any) {
  driverType.value = driver;
  loadDevices();
}

function toggleBlankPageOptions() {
  const enabled = delEmptyPage.value;
}

function toggleScanOptions() {
  const useUI = useOriginalUi.value;
  // const controls = ["dpi", "pagesize", "source", "bitdepth"];
  // controls.forEach(id => {
  //   const el = document.getElementById(id);
  //   if (el) el.disabled = useUI;
  // });
}

function toggleFormatOptions(val: any) {
  saveType.value = val;
}

// 扫描
function scan() {
  if (!scanDevice.value) {
    proxy.$message.warning("请选择扫描设备！");
    return;
  }
  // saveProfile(false);
  if (initCount.value == 1 && firstCount.value) {
    fullTextFileNameHandle("init"); // 计数等于1的时候相当于没有添加
    firstCount.value = false;
  } else {
    fullTextFileNameHandle("");
  }
  const requestData = {
    driver: driverType.value,
    device: scanDevice.value,
    use_native_ui: useOriginalUi.value, // 使用扫描仪原生界面
    origin_name: currentConfig.value, // 当前配置
    profile_name: configName.value, // 配置名称
    source: sourceValue.value, // 扫描来源
    pagesize: pagesize.value, // 纸张大小
    dpi: dpi.value, // dpi像素
    bitdepth: bitdepth.value // 像素类型
  };
  loading.value = true;
  fetch(getSysConfig("fileScan"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(requestData)
  })
    .then(res => res.json())
    .then(result => {
      if (result.images) {
        result.images.forEach((url: string) => {
          const img = document.createElement("img");
          img.src = `${getSysConfig("fileScanImageOrigin")}${url}`;
          img.style.width = "200px";
          img.style.margin = "5px";
          img.style.border = "1px solid #ccc";
          img.title = `${getSysConfig("fileScanImageOrigin")}${url}`;
          images.value.push(img);
          imagesUrls.value.push(`${getSysConfig("fileScanImageOrigin")}${url}`);
          curNodeImgUrl.value = `${getSysConfig("fileScanImageOrigin")}${url}`;
          setTimeout(() => {
            curImgIndex.value = imagesUrls.value?.length - 1;
            scrollToBottom();
            loading.value = false;
          }, 1000);
          if (props.scanFrom != "FullText") {
            uploadScanFile();
          } else {
            // handleChangeFile();
          }
        });
      } else if (result.message) {
        console.log(result.message);
        loading.value = false;
      } else if (result.error) {
        console.log(result.error);
        loading.value = false;
      }
    })
    .catch(error => {
      console.log(error);
      loading.value = false;
    });
}

// 上传文件
const uploadScanFile = async () => {
  // 1. 获取 Blob
  const fullUrl = curNodeImgUrl.value;

  // 2. 转换为 Blob
  const fileBlob = await getFileBlob(fullUrl);
  if (!fileBlob) return;

  // 3. 转换为 File 对象（可选）
  const file = new File([fileBlob], `${fileName.value}.${saveType.value}`, { type: fileBlob.type });

  // 4. 上传
  const uploadResult = await uploadFile(file);
  console.log("上传成功:", uploadResult);

  // 辅助函数
  async function getFileBlob(url: string) {
    const response = await fetch(url);
    if (!response.ok) throw new Error("文件获取失败");
    return await response.blob();
  }

  async function uploadFile(file: any) {
    const formData = new FormData();
    formData.append("file", file);

    axios({
      url: `api/api/MasterFile/files?path=${fileDirectory.value}`,
      method: "post",
      data: formData
    }).then(res => {
      console.log("文件上传成功!!!", res);
      getTreeNodeData();
    });
  }
};

// 处理节点数据
const adaptTreeData = (apiData: any) => {
  return (apiData.Children || []).map((item: any) => ({
    label: item.Name,
    name: item.Name,
    path: item.Path,
    isDirectory: item.IsDirectory,
    size: item.Size,
    children: item.IsDirectory ? adaptTreeData(item) : null,
    rawData: item
  }));
};

// 获取节点数据
const getTreeNodeData = () => {
  return axios
    .get("api/api/MasterFile/files", {
      params: {
        path: "",
        recursive: true
      }
    })
    .then((res: any) => {
      console.log("先获取一下节点数据---", res.data);
      filenodes.value = adaptTreeData(res.data);
      return filenodes.value;
    });
};

// 下载
function downloadScanned(type: string) {
  // 没有图片可供下载
  if (!imagesUrls.value.length) {
    console.log("没哟图片可供下载");
    return;
  }
  const params = {
    format: saveType.value,
    images: imagesUrls.value.map((url: string) => {
      // 方式 1：用 replace 去掉前缀
      return url.replace(/^https?:\/\/[^/]+\//, "");
      // 结果: scans/scan_20250817_153117_%d.jpg
    }),
    jpeg_quality: imageQuality.value,
    tiff_compression: tifZipStyle.value,
    group_num: splitCount.value
  };

  fetch(getSysConfig("fileScanDownload"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params)
  })
    .then(res => {
      if (!res.ok) throw new Error("下载失败");

      const disposition = res.headers.get("content-disposition");
      let filename = fileName.value;
      if (disposition && disposition.includes("filename=")) {
        filename = disposition.split("filename=")[1].replace(/["']/g, "").trim();
      }
      return res.blob().then(blob => ({ blob, filename }));
    })
    .then(({ blob, filename }) => {
      if (type == "upload") {
        const file = new File([blob], `${fileName.value}.${splitCount.value ? "zip" : saveType.value}`, { type: blob.type });
        mittBus.emit("scanFileUpload", [file]);
        return;
      }
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    })
    .catch(err => {
      alert("下载失败：" + err.message);
    });
}

// 点击导入
const uploadFile = () => {
  fileInput.value.click();
};

const handleFileChange = (event: any) => {
  const files: any = Array.from(event.target.files); // 转为数组方便操作
  if (!files.length) return;

  const formData = new FormData();
  for (let file of files) {
    formData.append("files", file);
  }

  if (initCount.value == 1 && firstCount.value) {
    fullTextFileNameHandle("init"); // 计数等于1的时候相当于没有添加
    firstCount.value = false;
  } else {
    fullTextFileNameHandle("");
  }

  fetch(getSysConfig("fileScanImportImage"), {
    method: "POST",
    body: formData
  })
    .then(res => res.json())
    .then(result => {
      if (result.error) {
        proxy.$message.error("上传失败!");
      } else if (result.images) {
        result.images.forEach((url: string) => {
          const img = document.createElement("img");
          img.src = `${getSysConfig("fileScanImageOrigin")}${url}`;
          img.style.width = "200px";
          img.style.margin = "5px";
          img.style.border = "1px solid #ccc";
          img.title = `${getSysConfig("fileScanImageOrigin")}${url}`;
          images.value.push(img);
          imagesUrls.value.push(`${getSysConfig("fileScanImageOrigin")}${url}`);
          curNodeImgUrl.value = `${getSysConfig("fileScanImageOrigin")}${url}`;
        });
        proxy.$message.success("导入成功！");
        setTimeout(() => {
          scrollToBottom();
        }, 1000);
      }
    })
    .catch(err => {
      proxy.$message.error("上传失败!");
    });
};

const clearImages = () => {
  // imagesUrls.value = [];
  // curNodeImgUrl.value = ""
  delAllPage();
};

// 删除单个页面
const delSinglePage = () => {
  if (!imagesUrls.value.length) return;
  proxy.$confirm("是否删除该页？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    callback: function (value: string) {
      if (value == "confirm") {
        const index = imagesUrls.value?.findIndex((item: string) => item == curNodeImgUrl.value);
        imagesUrls.value?.splice(index, 1);
      }
    }
  });
};

// 删除多个页面
const delAllPage = () => {
  if (!imagesUrls.value.length) return;
  proxy.$confirm("是否删除全部？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    callback: function (value: string) {
      if (value == "confirm") {
        imagesUrls.value = [];
        curNodeImgUrl.value = "";
      }
    }
  });
};

// 缩放处理
const scaleHandle = (count: number) => {
  if (!curNodeImgUrl.value) return;
  cropperRef.value?.changeScale(count);
  if (count > 0) {
    curScaleValue.value += 10;
  } else {
    curScaleValue.value -= 10;
  }
};

// 开始裁剪
const start = () => {
  if (!curNodeImgUrl.value) return;
  cropperRef.value?.start();
};

// 裁剪
const trimClick = () => {
  if (!curNodeImgUrl.value) return;
  cropperRef.value?.trimClick();
};

// 旋转处理
const rotateHandle = (type: string) => {
  if (!curNodeImgUrl.value) return;
  if (type == "left") {
    cropperRef.value?.rotateLeft();
  } else {
    cropperRef.value?.rotateRight();
  }
};

// 重置
const reset = () => {
  if (!curNodeImgUrl.value) return;
  cropperRef.value?.reset();
};

const defaultDirectNameSuffix = "FN-2025-Y"; // 默认文件夹的前缀
let directSuffixCount = 1; // 文件夹默认开始数字
let fileSuffixCount = 0; // 文件默认开始数字

// 更新目录名称
const handleChangeDic = async () => {
  directSuffixCount += 1;
  // ✅ 文件夹数字也补齐四位
  fileDirectory.value = `${defaultDirectNameSuffix}-${directSuffixCount.toString().padStart(4, "0")}`;
  fileSuffixCount = 0; // 文件数字重置

  // 使用4位补零格式初始化文件名
  fileName.value = `${fileDirectory.value}_${initCount.value.toString().padStart(4, "0")}`;

  // 扫描区域重置
  imagesUrls.value = []; // 缩略图区域清空
  curNodeImgUrl.value = ""; // 当前扫描大图清空
  initCount.value = 1; // 刷新目录之后，计数器重置为1

  const result = await getTreeNodeData();
  if (result && result?.length) {
    const isExit = result?.filter((item: any) => item.name == fileDirectory.value).length;
    if (isExit) {
      // 目录已存在，不需要往下走
      return;
    }
  }

  updateDirectory();
};

// 更新数据库文件夹
const updateDirectory = () => {
  axios({
    url: `/api/api/MasterFile/folders?path=${fileDirectory.value}`,
    method: "post"
  }).then(res => {
    console.log("res---", res);
  });
};

// 更新文件名称
const handleChangeFile = () => {
  // console.log("更新文件名称");
  // fileSuffixCount += 1;
  // const value = fileSuffixCount < 10 ? `${fileDirectory.value}_0${fileSuffixCount}` : `${fileDirectory.value}_${fileSuffixCount}`;
  // fileName.value = value;
  // console.log("当前文件名称fileName.value--", fileName.value);
  fullTextFileNameHandle("add");
};

const fullTextFileNameHandle = (type: string) => {
  if (type === "init") {
    if (props.scanFrom == "FullText") {
      // 初始化文件名（不带序号）
      fileName.value = props.fatherObj.Code;
    }
    if (props.scanFrom == "FullText") {
      // 设置初始序号（0001）
      initCount.value = 1;
      fileName.value = `${fileName.value}_${initCount.value.toString().padStart(4, "0")}`;
    } else {
      // 提取基础文件名（去掉旧序号）
      const baseName = fileName.value.split("_")[0];
      // 更新文件名（baseName + 新序号）
      fileName.value = `${baseName}_${initCount.value.toString().padStart(4, "0")}`;
    }

    return;
  }

  // 递增序号
  initCount.value += 1;
  // 提取基础文件名（去掉旧序号）
  const baseName = fileName.value.split("_")[0];
  // 更新文件名（baseName + 新序号）
  fileName.value = `${baseName}_${initCount.value.toString().padStart(4, "0")}`;
};

onMounted(() => {
  if (props.scanFrom == "FullText") {
    fullTextFileNameHandle("init");
  } else {
    updateDirectory(); // 在非全文的状态下才需要更新文件夹树
  }
  mittBus.on("fileUploadEnd", () => {
    // 注册一个监听文件上传的函数
    imagesUrls.value = [];
    curNodeImgUrl.value = "";
    initCount.value = 1; // 刷新目录之后，计数器重置为1
  });
  loadDevices();
  loadProfileList();
  toggleScanOptions();
  toggleBlankPageOptions();
  toggleFormatOptions("jpg");
  getTreeNodeData();
});
</script>
<style lang="scss" scoped>
.file-scan {
  height: 100%;
  .el-card {
    height: 100%;
    .left-top {
      display: flex;
      align-items: center;
      height: 35px;
      color: #ffffff;
      background-color: rgb(0 150 136);
      .left {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 200px;
        padding-right: 8px;
        .icons-item {
          display: flex;
          align-items: center;
        }
        .current-page {
          font-size: 16px;
        }
      }
      .right {
        display: flex;
        align-items: center;
        .el-icon {
          cursor: pointer;
        }
        .scale {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 110px;
          padding: 0 8px;
          border-right: 1px solid #ffffff;
          border-left: 1px solid #ffffff;
        }
        .right-icons {
          display: flex;
          align-items: center;
          margin-left: 40px;
        }
      }
      .iconfont {
        margin: 0 8px;
        font-size: 24px;
      }
      .icon-piliangshanchu {
        font-size: 20px;
      }
      .icon-1bi1huanyuan {
        font-size: 30px;
      }
      .icon-icon {
        margin-top: -4px;
      }
      .icon-pingyi {
        font-size: 22px;
      }
      .icon-shipeifangshi-zishiying {
        font-size: 28px;
      }
      .icon-zuoshunshizhenxuanzhuan,
      .icon-youshunshizhenxuanzhuan {
        font-size: 20px;
      }
    }
    .left-content {
      display: flex;
      height: calc(100% - 35px);
      .small-previw {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 200px;
        padding-bottom: 10px;
        overflow-y: auto;
        border-right: 1px solid var(--el-bg-color-page);
        .preview-item {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 90%;
          height: 230px;
          padding: 10px;
          margin-top: 20px;
          cursor: pointer;
          border: 2px solid #cccccc;
          &:hover {
            border-color: rgb(0 150 136);
          }
          img {
            width: 100%;
          }
          .order {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 30px;
            height: 30px;
            line-height: 30px;
            color: #666666;
            text-align: center;
            background-color: #ffffff;
            border: 1px solid #cccccc;
            border-radius: 50%;
          }
        }
      }
      .big-preview {
        flex: 1;
      }
    }
  }
}
.right-title {
  height: 35px;
  padding: 0 10px;
  font-size: 14px;
  line-height: 35px;
  color: #ffffff;
  background-color: rgb(0 150 136);
}
.top-wrap {
  height: 57%;
}
.top-config {
  height: calc(100% - 35px);
  overflow-y: auto;
}
.config-item {
  padding: 8px 8px 0;
  .label {
    width: 100px;
    margin-bottom: 6px;
  }
  .content {
    display: flex;
    align-items: center;
    height: auto !important;
    margin-top: 6px;
    .pointer {
      align-items: flex-end;
      font-size: 20px;
    }
    .el-icon {
      margin-left: 8px;
      font-size: 23px;
      cursor: pointer;
    }
  }
}
.verticle-item {
  display: flex;
  align-items: center;
  padding: 8px 8px 0;
  .label {
    width: 110px;
  }
}
.btn-wrap {
  height: 39%;
  margin-top: 20px;
  .btn-group {
    display: flex;
    flex-direction: column;
    height: calc(100% - 35px);
    padding: 8px;
    margin-top: 10px;
    overflow-y: auto;
    .el-button {
      margin-bottom: 10px;
      margin-left: 0;
    }
  }
}
.el-button {
  i {
    margin-right: 4px;
  }
}
:deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
}
:deep(.el-drawer__body) {
  padding: 6px;
  .el-card {
    height: auto;
    margin-bottom: 20px;
    .basic-config {
      display: flex;
      flex-direction: column;
      padding: 6px;
      .basic-item {
        margin-bottom: 10px;
        .label {
          margin-bottom: 6px;
        }
      }
    }
    .scan-config {
      display: flex;
      flex-direction: column;
      padding: 6px;
      .scan-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        .label {
          width: 88px;
        }
      }
    }
  }
  .save-config {
    width: 100%;
    margin-bottom: 10px;
  }
}
.high-config {
  display: flex;
  flex-direction: column;
  padding: 6px;
  .el-checkbox {
    min-width: 140px;
    margin-right: 0;
  }
  .empty-page {
    .config-value {
      margin: 8px 0 0;
      span {
        display: block;
        margin-bottom: 6px;
      }
    }
  }
}
.upload-btn {
  i {
    font-size: 18px;
  }
}
.splitCount {
  display: flex;
  align-items: center;
}
</style>
